﻿// Copyright (c) 2017 GlassGrass

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UniRx;



namespace GlassGrass.Unity.GuiFramework
	{
	/// <summary> Editable text field. </summary>
	public class TextField : GuiElement
		{
		#region events

		/// <summary> Be fired when this text was changed. </summary>
		public IObservable<string> TextChanged => _textChanged.DistinctUntilChanged();
		private readonly  Subject<string> _textChanged = new Subject<string>();

		#endregion


		#region fields and properties

		/// <summary> [get/set] Text of GUI content. </summary>
		public override string Text
			{
			get => base.Text;
			set
				{
				base.Text = value;
				_textChanged.OnNext(value);
				}
			}

		#endregion



		/// <summary> Create TextField instance. </summary>
		/// <param name="config"> [Non-Nullable] </param>
		/// <exception cref="System.ArgumentNullException"></exception>
		public TextField(GuiConfig config)
			: base(config)
			{
			}



		/// <summary> Define what to choose style for this from skin. </summary>
		/// <param name="skin"></param>
		/// <returns></returns>
		protected override GUIStyle ChooseStyle(GUISkin skin)
			=> skin?.textField;



		/// <summary> Define how to layout manually itself on rendering frame. </summary>
		/// <param name="parentSkin"></param>
		public override void LayoutManual(GUISkin parentSkin)
			{
			Text = GUI.TextField(Rect, Text, SelectValidStyle(parentSkin));
			}



		/// <summary> Define how to layout automatically itself on rendering frame.  </summary>
		/// <param name="parentSkin"></param>
		public override void LayoutAuto(GUISkin parentSkin)
			{
			Text = GUILayout.TextField( Text, SelectValidStyle( parentSkin ), LayoutOptions );
			}



		/// <summary> Begin 'Text' property binding. </summary>
		/// <typeparam name="TValue"> Type of model property. </typeparam>
		/// <param name="modelObj"> Model object instance. </param>
		/// <param name="propertyName"> Model object property for binding. </param>
		/// <param name="converter"> Value converter. </param>
		/// <returns></returns>
		public override Binding<TValue, string> BeginBinding<TValue>(object modelObj, string propertyName, IValueConverter<TValue, string> converter = null)
			=> GuiBindingFactory.BeginBinding<TValue, string>(modelObj, propertyName, this, nameof(Text), converter, TextChanged);

		}
	}
